import { defineStore } from 'pinia'
import type { Instruction } from '@/types/AIResponse'

/**
 * 指令执行结果接口
 */
export interface InstructionResult {
  /**
   * 关联的指令ID
   */
  instructionId: string

  /**
   * 指令类型
   */
  action: string

  /**
   * 图层类型
   */
  layerType: string

  /**
   * 执行时间
   */
  executedAt: number

  /**
   * 执行状态
   */
  status: 'success' | 'failed'

  /**
   * 执行结果数据
   */
  resultData: any

  /**
   * 错误信息（如果执行失败）
   */
  errorMessage?: string
}

// 存储指令执行结果
export const useInstructionResultStore = defineStore('instructionResult', {
  state: () => ({
    results: [] as InstructionResult[],
  }),
  getters: {
    /**
     * 获取所有指令执行结果
     */
    getAllResults(): InstructionResult[] {
      return this.results
    },

    /**
     * 获取最近的N条执行结果
     */
    getRecentResults: (state) => (count: number) => {
      return [...state.results].sort((a, b) => b.executedAt - a.executedAt).slice(0, count)
    },

    /**
     * 根据指令类型获取执行结果
     */
    getResultsByAction: (state) => (action: string) => {
      return state.results.filter(result => result.action === action)
    },

    /**
     * 获取查询类指令的结果
     */
    getQueryResults: (state) => {
      return state.results.filter(result =>
        result.action === 'QUERY_FEATURE' ||
        result.action === 'QUERY_SURROUNDING'
      )
    },

    /**
     * 获取特定要素的查询结果
     */
    getFeatureQueryResult: (state) => (featureName: string) => {
      return state.results.find(result =>
        (result.action === 'QUERY_FEATURE' &&
         result.resultData?.attributes?.name === featureName) ||
        (result.resultData?.attributes?.BuildingName === featureName) ||
        (result.resultData?.attributes?.RoadName === featureName) ||
        (result.resultData?.attributes?.AreaName === featureName)
      )
    },

    /**
     * 获取周边设施查询结果
     */
    getSurroundingResults: (state) => (longitude?: number, latitude?: number) => {
      if (longitude && latitude) {
        // 如果提供了经纬度，查找匹配的结果
        return state.results.filter(result =>
          result.action === 'QUERY_SURROUNDING' &&
          result.resultData?.surroundingParams?.longitude === longitude &&
          result.resultData?.surroundingParams?.latitude === latitude
        )
      } else {
        // 否则返回所有周边查询结果
        return state.results.filter(result => result.action === 'QUERY_SURROUNDING')
      }
    },
  },
  actions: {
    /**
     * 添加指令执行结果
     */
    addResult(result: InstructionResult) {
      this.results.push(result)
    },

    /**
     * 批量添加指令执行结果
     */
    addResults(results: InstructionResult[]) {
      this.results.push(...results)
    },

    /**
     * 清空所有结果
     */
    clearResults() {
      this.results = []
    },

    /**
     * 删除特定指令的执行结果
     */
    removeResult(instructionId: string) {
      const index = this.results.findIndex(r => r.instructionId === instructionId)
      if (index !== -1) {
        this.results.splice(index, 1)
      }
    },

    /**
     * 更新指令执行结果
     */
    updateResult(instructionId: string, updatedData: Partial<InstructionResult>) {
      const index = this.results.findIndex(r => r.instructionId === instructionId)
      if (index !== -1) {
        this.results[index] = { ...this.results[index], ...updatedData }
      }
    },
  },
})